package com.szxw.BaiduAi.controller;


import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Base64Util;

import com.szxw.BaiduAi.service.SpeechService;
import com.szxw.BaiduAi.utils.FileUtils;
import com.szxw.BaiduAi.utils.MethodUtils;
import org.json.JSONObject;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @Author: 苏执小威
 * @Email:1410511702@qq.com
 * @Desc: 语音识别模块
 * @Date: 2022/9/20 16:27
 */
@WebServlet("/speech")
public class SpeechController extends BaiDuController {
    private SpeechService service = new SpeechService();

    /**
     * 该方法用于实现 语音合成
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void voiceSpeech(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取参数
        String text = req.getParameter("text");
        String pit = req.getParameter("pit");
        String spd = req.getParameter("spd");
        String per = req.getParameter("per");
        String vol = req.getParameter("vol");

        TtsResponse synthesis = service.synthesis(text, spd, pit, per, vol);
        byte[] data = synthesis.getData();
        String encode = Base64Util.encode(data);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", encode);
        MethodUtils.close(resp, jsonObject);
    }
    /**
     * 该方法用于实现 语音合成
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void speechDiscren(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        byte[] files = FileUtils.getFileDataByRequest(req);
        JSONObject asr = service.asr(files);
        MethodUtils.close(resp,asr);


    }
}
